package com.hmall.order.service.impl;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.Feign.ItemFeign.Itemfeign;
import com.hmall.common.Feign.UserFeign.Userfeign;
import com.hmall.order.mapper.OrderMapper;
import com.hmall.order.pojo.*;
import com.hmall.order.service.IOrderService;
import com.hmall.order.utils.RabbitMQConfig;
import com.hmall.user.pojo.Address;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class OrderService extends ServiceImpl<OrderMapper, Order> implements IOrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private Userfeign userfeign;
    @Autowired
    private Itemfeign itemfeign;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    private long workerId = 0;
    private long datacenterId = 1;
    private Snowflake snowflake = IdUtil.createSnowflake(workerId, datacenterId);//雪花算法

    @GlobalTransactional
    @Override
    public Long insert(OrderDTO orderDTO) {
        Long itemId = orderDTO.getItemId();
        //查询商品信息
        Item item = orderMapper.findById(itemId);
        //计算商品总价
        Integer totalFee = Math.toIntExact(item.getPrice() * orderDTO.getNum());
        //创建Order
        Order order = new Order();
        order.setTotalFee(totalFee.longValue());
        order.setStatus(1);
        order.setPaymentType(orderDTO.getPaymentType());
        order.setUserId(2l);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = simpleDateFormat.format(new Date());
        try {
            Date creatDate = simpleDateFormat.parse(format);
            order.setCreateTime(creatDate);
            order.setUpdateTime(creatDate);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        long orderid = snowflake.nextId();
        order.setId(orderid);
        orderMapper.insert(order);
        //封装OrderDetail对象
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setOrderId(orderid);
        orderDetail.setItemId(item.getId());
        orderDetail.setNum(orderDTO.getNum());
        orderDetail.setTitle(item.getName());
        orderDetail.setSpec(item.getSpec());
        orderDetail.setPrice(item.getPrice());
        orderDetail.setImage(item.getImage());
        try {
            Date creatDate = simpleDateFormat.parse(format);
            orderDetail.setCreateTime(creatDate);
            orderDetail.setUpdateTime(creatDate);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        orderMapper.into(orderDetail);
        //MQ
        rabbitTemplate.convertAndSend(RabbitMQConfig.TTL_EXCHANGE,"ttl.test",order.getId());
        //查询address并封装成OrderLogistics
        try {
            Date creatDate = simpleDateFormat.parse(format);
            Address address=userfeign.findAddressById(orderDTO.getAddressId());
            OrderLogistics orderLogistics=OrderLogistics.builder().orderId(orderid)
                    .contact(address.getContact())
                    .phone(address.getMobile())
                    .province(address.getProvince())
                    .city(address.getCity())
                    .town(address.getTown())
                    .street(address.getStreet())
                    .createTime(creatDate)
                    .updateTime(creatDate).build();
            orderMapper.savein(orderLogistics);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        //当状态为支付时减库存
        if (order.getStatus() ==2) {
            itemfeign.reduce(orderid,orderDTO.getNum().longValue());
        }
        return orderid;
    }
}
